package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {

        log.info("上传的数据：{},{},{}", username, age, image);

        // 获取原始文件名 - 1.png   123.0.0.png
        String originalFilename = image.getOriginalFilename();

        // 构建唯一的文件名（不能重复） - uuid（通用唯一识别码） 52985c69-8710-40f8-8cbd-76d7f0f2cca0
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFilename = UUID.randomUUID().toString() + extname;

        log.info("新文件名：{}", newFilename);

        // 将文件存储在服务器的吸盘目录中
        image.transferTo(new File("E:\\JavaWeb\\uploads\\" + newFilename));

        return Result.success();
    }

}
